import axios from "axios";
import Message from "@/components/Message/message.js";

const http = axios.create({
  baseURL: "/api",
});

/**
 *  登录之后，会在发送请求时自动携带authorization信息
 */
http.interceptors.request.use((configs) => {
  try {
    let data = JSON.parse(localStorage.getItem("user"));

    if (data && data.authorization) {
      configs.headers.common.authorization = data.authorization;
    }
  } catch (e) {
    console.log(e);
  }
  //  一定要记得将 configs 返回出去
  return configs;
});

/**
 *  响应拦截器， 遇到错误就将详情抛出
 *
 */
http.interceptors.response.use(
  (response) => {
    return response;
  },
  (error) => {
    let { errorDetails, message } = error.response.data;
    Message.error(`${message}, ${errorDetails}`);
    throw new Error(message);
  }
);

/**
 * 注册新用户胡
 *
 * @param {{name:string, password:string}} data
 */
export const register = (data) => {
  return http.post("/user/register", data);
};

/**
 * 用户登录
 *
 * @param {{name:string, password:string}} data
 */
export const login = (data) => {
  return http.post("/user/login", data);
};

/**
 *  获取所有面板
 *
 */

export const getBoards = () => {
  return http.get("/board");
};

/**
 *  获取指定面板
 *
 */
export const getBoard = (id) => {
  return http.get(`/board/${id}`);
};

/**
 *  创建新面板
 *
 */

export const postBoard = (data) => {
  return http.post("/board", data);
};

/**
 *  获取所在面板对应的列表
 *
 */

export const getLists = (boardId) => {
  return http.get(`/list`, {
    params: {
      boardId,
    },
  });
};

/**
 *  添加一个新的列表
 *
 */

export const postList = (data) => {
  return http.post("/list", data);
};

/**
 *  修改一个列表的排序
 *
 */

export const putList = (data) => {
  return http.put(`/list/${data.id}`, data);
};

/**
 *  获取列表下的所有卡片
 *
 */

export const getCards = (boardListId) => {
  return http.get(`/card`, {
    params: {
      boardListId,
    },
  });
};

/**
 *  创建新卡片
 *
 */

export const postCard = (data) => {
  return http.post("/card", data);
};

/**
 *  编辑一张指定的卡片
 *
 */

export const putCard = (data) => {
  return http.put(`/card/${data.id}`, data);
};

/**
 *  上传附件
 *
 */

export const uploadAttachment = (data) => {
  let fd = new FormData();

  fd.append("boardListCardId", data.boardListCardId);
  fd.append("attachment", data.file);

  return http.post(`/card/attachment`, fd);
};

/**
 *  删除附件
 *
 */

export const removeAttachment = (data) => {
  return http.delete(`/card/attachment/${data.id}`);
};

/**
 *   设置封面
 *
 */

export const setCover = (data) => {
  return http.put(`/card/attachment/cover/${data.id}`);
};

/**
 *  移除封面
 *
 */

export const removeCover = (data) => {
  return http.delete(`/card/attachment/cover/${data.id}`);
};

/**
 *  获取评论列表
 *
 */

export const getComments = (params) => {
  return http.get(`/comment`, {
    params,
  });
};

/**
 *   发表评论
 *
 */

export const postComment = (body) => {
  return http.post(`/comment`, body);
};
